<template>
  <Form ref="form" :model="entity" :rules="rules" :label-width="90">
    <Row>
      <Col :span="12">
        <FormItem :label="l('tableDescription')" prop="tableDescription">
          <InputYi v-model="entity.tableDescription" @on-yi="quite">
          </InputYi>
        </FormItem>
      </Col>
      <Col :span="12">
        <FormItem :label="l('base')" prop="base">
          <dictionary code="System.DbEnityDefined.Base" v-model="entity.base" type="radio" />
        </FormItem>
      </Col>
      <Col :span="4">
        <FormItem :label="l('dbTableName')" prop="dbTableName">
          <Input v-model="entity.dbTableName"></Input>
        </FormItem>
      </Col>
      <Col :span="4">
        <FormItem :label="l('entityName')" prop="entityName">
          <Input v-model="entity.entityName"></Input>
        </FormItem>
      </Col>

      <Col :span="4">
        <FormItem :label="l('dbFullName')" prop="dbFullName">
          <Input v-model="entity.dbFullName"></Input>
        </FormItem>
      </Col>
      <Col :span="12">
        <FormItem :label="l('methods')" prop="methods">
          <Dictionary code="System.DbEnityDefined.Methods" v-model="entity.methods" type="checkbox"></Dictionary>
        </FormItem>
      </Col>
      <Col :span="6">
        <FormItem :label="l('status')" prop="status">
          <Dictionary code="System.DbEnityDefined.Status" v-model="entity.status" type="radio"></Dictionary>
        </FormItem>
      </Col>
      <Col :span="24">
        <Tabs>
          <Checkbox slot="extra" v-model="mode">高级</Checkbox>
          <TabPane label="属性定义">
            <Table :columns="curColumns" border class="editTable" :data="list">
              <template slot="columnDescription" slot-scope="{row,index}">
                <Input v-model="row.columnDescription" @on-change="setRow(row,index)">
                  <span slot="append" @click="fanyi(row,index)">译</span>
                </Input>
              </template>
              <template slot="inputType" slot-scope="{row,index}">
                <Dictionary
                  code="System.DbEnityDefined.Control"
                  v-model="row.inputType"
                  @on-change="setInputType(row,index)"
                />
              </template>
              <template slot="dataType" slot-scope="{row,index}">
                <Dictionary
                  code="System.DbEnityDefined.DataType"
                  v-model="row.dataType"
                  @on-change="setRow(row,index)"
                />
              </template>
              <template slot="dbColumnName" slot-scope="{row,index}">
                <Input v-model="row.dbColumnName" @on-change="setRow(row,index)" />
              </template>
              <template slot="length" slot-scope="{row,index}">
                <Input v-model="row.length" @on-change="setRow(row,index)" />
              </template>
              <template slot="decimalDigits" slot-scope="{row,index}">
                <Input v-model="row.decimalDigits" @on-change="setRow(row,index)" />
              </template>
              <template slot="propertyName" slot-scope="{row,index}">
                <Input v-model="row.propertyName" @on-change="setRow(row,index)" />
              </template>
              <template slot="group" slot-scope="{row,index}">
                 <Input
                  v-model="row.group"
                  @on-change="setRow(row,index)"
                />
              </template>
              <template slot="propertyType" slot-scope="{row,index}">
                <Input v-model="row.propertyType" @on-change="setRow(row,index)" />
              </template>
              <template slot="defaultValue" slot-scope="{row,index}">
                <Input v-model="row.defaultValue" @on-change="setRow(row,index)" />
              </template>
              <template slot="code" slot-scope="{row,index}">
                <Input
                  v-if="row.inputType==4||row.inputType==8||row.inputType==9"
                  v-model="row.code"
                  @on-change="setRow(row,index)"
                />
              </template>
              <template slot="unit" slot-scope="{row,index}">
                <Dictionary
                  v-if="row.inputType==2"
                  code="System.DbEnityDefined.Unit"
                  v-model="row.unit"
                  @on-change="setRow(row,index)"
                />
              </template>
              <template slot="link" slot-scope="{row,index}">
                <Icon v-if="row.link==1" type="md-git-merge" />
              </template>
              <template slot="isNullable" slot-scope="{row,index}">
                <Checkbox v-model="row.isNullable" @on-change="setRow(row,index)" />
              </template>
              <template slot="isPrimarykey" slot-scope="{row,index}">
                <Checkbox v-model="row.isPrimarykey" @on-change="setRow(row,index)" />
              </template>
              <template slot="single" slot-scope="{row,index}">
                <Checkbox v-model="row.single" true-value="1" fasle-value="0" @on-change="setRow(row,index)" />
              </template>
              <template slot="rule" slot-scope="{row,index}">
                 <Input
                  v-model="row.rule"
                  @on-change="setRow(row,index)"
                />
              </template>
            </Table>
            <Row>
              <Col span="12">
                <Button type="dashed" class="mt2" @click="addRow">添加</Button>
              </Col>
               <Col span="12" class="tr">
               <Tag class="mt2" color="blue"> 快捷功能：</Tag>
                <Select v-model="tableId" v-width="400"  class="mt2">
                  <Option v-for="item in tables" :value="value" :key="item"></Option>
                </Select>
                  <Button type="default" class="mt2" @click="addRow">导入</Button>
                  <Button type="default" class="mt2" @click="addRow">外键</Button>
                  <Button type="default" class="mt2" @click="addRow">对象</Button>
                  <Button type="default" class="mt2" @click="addRow">对象集合</Button>
               </Col>
            </Row>
          </TabPane>
        </Tabs>
      </Col>
      <Col :span="24" class="mt5">
        <FormItem>
          <Button type="primary" @click="handleSubmit" double>保存</Button>
          <Button @click="handleClose" class="ml20">取消</Button>
        </FormItem>
      </Col>
    </Row>
  </Form>
</template>
<script>
import Api from "./api";
export default {
  name: "Add",
  data() {
    return {
      disabled: false,
      mode: true,
      tables:[],
      tableId:null,
      isNullable:true,
      entity: {
        base: "Auto", //编码
        dbFullName: "", //
        columns: null,
        methods: "Create,Update,List,Paged,Delete,Import,Group,Batch,List",
        nameRule: null,
        entityName: "",
        dbTableName: "", //编码
        tableDescription: "", //名称
        creationTime: null,
        creatorUserId: "",
        lastModificationTime: null,
        lastModifierUserId: "",
        deletionTime: null,
        deleterUserId: "",
        isDeleted: null,
        status: 0, //状态
        columns: [], //属性定义
      },
      row: {
        columnDescription: "",
        dbColumnName: "",
        dataType: "varchar",
        propertyName: "",
        propertyType: "",
        code: "",
        isNullable: true,
        isPrimarykey: false,
        unit: null,
        single:0,
        length: 50,
        decimalDigits: 0,
        link: 0,
        defaultValue: "",
        inputType: 0,
        rule:null
      },
      list: [],
      columns: [
        {
          type: "index",
          width: 60,
          align: "center",
        },
        {
          title: "数据库设置",
          children: [
            {
              key: "link",
              title: "关联",
              align: "center",
              width: 70,
              slot: "link",
            },
            {
              key: "isPrimarykey",
              title: "主键",
              align: "center",
              width: 70,
              slot: "isPrimarykey",
            },
            {
              key: "columnDescription",
              title: "名称",
              align: "left",
              slot: "columnDescription",
                 width: 180,
            },
            {
              key: "dbColumnName",
              title: "字段",
              align: "left",
              easy: true,
              hide: true,
              slot: "dbColumnName",
              width: 150,
            },
            {
              key: "inputType",
              title: "设置",
              align: "left",
              slot: "inputType",
              width: 150,
            },
            {
              key: "dataType",
              title: "数据类型",
              align: "left",
              hide: true,
              width: 150,
              slot: "dataType",
            },
            {
              key: "length",
              title: "长度",
              align: "left",
              hide: true,
              width: 100,
              slot: "length",
            },
            {
              key: "decimalDigits",
              title: "小数位数",
              align: "left",
              width: 100,
              hide: true,
              slot: "decimalDigits",
            },
            {
              key: "defaultValue",
              title: "默认值",
              align: "left",
              width: 100,
              hide: true,
              slot: "defaultValue",
            },
            {
              key: "isNullable",
              title: "可空",
              align: "center",
              width: 70,
              slot: "isNullable",
            },
          ],
        },
        {
          title: "业务设置",
          hide:true,
          children: [
            {
              key: "group",
              title: "关联对象",
              align: "left",
              width: 100,
              hide: true,
              slot: "group",
            },
            {
              key: "propertyName",
              title: "属性名",
              align: "left",
              hide: true,
              width: 100,
              slot: "propertyName",
            },
            // {
            //   key: "propertyType",
            //   title: "属性类型",
            //   align: "left",
            //   width: 100,
            //   hide: true,
            //   slot: "propertyType",
            // },
            {
              key: "code",
              title: "数据编码",
              align: "left",
              slot: "code",
            },
            {
              key: "unit",
              title: "单位",
              align: "left",
              slot: "unit",
              width: 100,
            },
            {
              key: "single",
              title: "唯一",
              align: "left",
              slot: "single",
              width: 70,
            },
            {
              key: "rule",
              title: "校验",
              align: "left",
              slot: "rule",
              width: 150,
            },
          ],
        },

        {
          title: "操作",
          key: "action",
          width: 80,
          align: "center",
          render: (h, params) => {
            return h("div", { class: "action" }, [
              h(
                "op",
                {
                  attrs: { oprate: "delete" },
                  on: { click: () => this.remove(params) },
                },
                "删除"
              ),
            ]);
          },
        },
      ],
      rules: {
        tableDescription: [{ required: true, message: "必填", trigger: "blur" }],
      },
    };
  },
  props: {
    v: Object,
    eid: String,
  },
  mounted() {
    if (this.eid) {
      this.load(this.eid);
    }
  },
  methods: {
    checkIsNullabled(v){
      this.isNullable=v;
      this.list.map((u,i)=>{
        u.isNullable=v;
        this.$set(this.list,i,u)
      })
    },
    handleSubmit() {
      this.$refs.form.validate((v) => {
        if (v) {
           /// 基础字段
        /// 0 业务字段
        /// 1 扩展字段
        /// 2 系统字段
          var baseTypes=["Table","View","Auto","Base"]
          this.entity.columns = this.list.map(u=>{
            u.baseType=0;
            if(this.entity.base=="Base"){
              u.baseType=2;
            }
            return u;
          });
          Api.create(this.entity)
            .then((r) => {
              if (r.success) {
                this.$Message.success("保存成功");
                this.$emit("on-ok");
              } else {
                this.$Message.error("保存失败");
              }
            })
            .catch((err) => {
              this.$Message.error("保存失败");
              console.warn(err);
            });
        }
      });
    },
    handleClose() {
      this.$emit("on-close");
    },
    quite(v){
      this.entity.dbTableName=v;
      this.entity.entityName=v;
    },
    async yi(){
       let {translateResult}= await Api.yi({i:this.entity.tableDescription});
      var result=translateResult[0][0]["tgt"];
    },
    addRow() {
      var row = this.$u.clone(this.row);
      let max = 1;
      this.list.map((u) => {
        var num = u.dbColumnName.replace(/[^0-9]/gi, "");
        if (num != "") {
          num = parseInt(num);
          if (num >= max) {
            max = num + 1;
          }
        }
      });
      row.dbColumnName = "c" + max;
      this.list.push(row);
    },
    setRow(row, index) {
      this.$set(this.list, index, row);
    },
    setInputType(row, index) {
      var sets = [
        {
          dataType: "varchar",
          length: 50,
          link: 0,
        },
        {
          dataType: "varchar",
          length: 2000,
          link: 0,
        },
        {
          dataType: "int",
          length: 0,
          decimalDigits: 0,
          link: 0,
        },
        {
          dataType: "datetime",
          length: 0,
          link: 0,
        },
        {
          dataType: "smallint",
          length: 0,
          link: 0,
        },
        {
          dataType: "text",
          length: 0,
          link: 0,
        },
        {
          dataType: "varchar",
          length: 200,
          link: 0,
        },
        {
          dataType: "varchar",
          length: 51,
          link: 0,
        },
        {
          dataType: "varchar",
          length: 52,
          link: 1,
        },
      ];
      row = Object.assign(row, sets[row.inputType]);
      this.$set(this.list, index, row);
    },
    load(v) {
      Api.get({ id: v }).then((r) => {
        this.entity = r.result;
        this.entity.id = 0;
      });
    },
    remove(para) {
      console.warn(para);
      this.list.splice(para.index, 1);
    },
    fanyi(row,index){
      
    },
    l(key) {
      key = "DbEntityDefined" + "." + key;
      return this.$t(key);
    },
  },
  computed: {
    curColumns() {
      if (this.mode) return this.columns;
      return this.columns.filter(u=>{
        return !u.hide;
      });
    },
  },
  watch: {
    v() {
      this.entity = this.$u.clone(this.v);
    },
  },
};
</script>
<style lang="less">
.editTable {
  td ivu-table-cell {
    overflow: auto;
  }
}
</style>